Page({
  data: {
    orderId: '',
    amount: 0,
    selectedPayment: 'wechat', // 默认选择微信支付
    countdown: 60, // 1分钟倒计时
    countdownTimer: null,
    countdownStr: '01:00', // 倒计时显示字符串
    isExpired: false, // 是否已过期
    baseUrl: 'http://localhost:9205' // 后端接口地址
  },

  onLoad: function(options) {
    this.setData({
      orderId: options.orderId,
      amount: options.amount || '280' // 默认金额
    });
    this.startCountdown();
  },

  onUnload: function() {
    // 清除倒计时
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
    }
  },

  // 开始倒计时
  startCountdown: function() {
    const timer = setInterval(() => {
      let countdown = this.data.countdown - 1;
      if (countdown >= 0) {
        // 计算分钟和秒数
        const minutes = Math.floor(countdown / 60);
        const seconds = countdown % 60;
        // 格式化显示
        const countdownStr = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        this.setData({
          countdown: countdown,
          countdownStr: countdownStr
        });
      } else {
        clearInterval(timer);
        this.setData({
          isExpired: true,
          countdownStr: '00:00'
        });
        
        // 显示支付超时提示
        wx.showToast({
          title: '支付超时，订单已取消',
          icon: 'none',
          duration: 2000
        });
      }
    }, 1000);

    this.setData({
      countdownTimer: timer
    });
  },

  // 选择支付方式
  selectPayment: function(e) {
    const paymentType = e.currentTarget.dataset.type;
    this.setData({
      selectedPayment: paymentType
    });
  },

  // 确认支付
  confirmPayment: function() {
    if (this.data.isExpired) {
      wx.showToast({
        title: '支付已超时，请重新下单',
        icon: 'none'
      });
      return;
    }

    const that = this;
    
    // 先调用接口记录支付方式
    wx.request({
      url: `${this.data.baseUrl}/order/insertPayForm`,
      method: 'GET',
      data: {
        oid: this.data.orderId,
        payfrom: "微信支付"
      },
      success: (res) => {
        console.log('支付方式记录成功', res);
        
        // 模拟调用微信支付
        wx.showLoading({
          title: '支付处理中',
        });
        
        // 模拟支付过程（实际项目中应使用真实的微信支付API）
        setTimeout(() => {
          wx.hideLoading();
          
          // 支付成功，直接跳转到支付成功页面
          wx.redirectTo({
            url: '/pages/payment-success/index?orderId=' + that.data.orderId
          });
        }, 1500);
      },
      fail: (err) => {
        console.error('支付方式记录失败', err);
        wx.showToast({
          title: '支付请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
}); 